package com.nmh.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Arrays;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobleException {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        //根据异常类型来判断具体的错误
        if(exception.getMessage().contains("Duplicate entry")){
            String[] str=exception.getMessage().split(" ");
            String msg=str[2]+"用户已经存在了";
            return R.error("401",msg);
        }
        return R.error("401","未知的错误");
    }
    @ExceptionHandler(CustomException.class)//捕获这个类型的异常
    public R<String> exceptionHandler(CustomException exception){
        log.error(exception.getMessage());//抛出的异常信息
        //根据抛出的异常的信息来判断是哪种错误
        return R.error("401",exception.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> exceptionHandler(MethodArgumentNotValidException exception){
        String[] str=exception.getMessage().split(" ");
        return R.error("401",str[str.length-1]);
    }
}
